package com.anniljing.kotlionlearn.Basic.coroutine

import kotlinx.coroutines.*


public suspend fun delayFun(timeMills: Long) {
    delay(timeMills)
    println("In delay:${Thread.currentThread().name}")
    println("这是一个挂起函数")
}

fun main() {
//   startWithBlock()
    startWithAsync()
}

fun startCoroutineWith() {
    GlobalScope.launch {
        delayFun(1000L)
        println("Do suspend method after")
    }
    println("do suspend method later")
    Thread.sleep(2000L)
    println("do suspend method before")
}

fun startWithBlock() {
    runBlocking {
        println("Coroutine started!")   // 2
        delayFun(1000L)                    // 3
        println("Hello World!")
    }
    println("After launch!")
    Thread.sleep(2000L)
    println("Process end!")
}

fun startWithAsync() {
    runBlocking {
        val deferred: Deferred<String> = async {
            println("In async:${Thread.currentThread().name}")
            delayFun(1000L) // 模拟耗时操作
            return@async "Task completed!"
        }
        println("After async:${Thread.currentThread().name}")
        val result = deferred.await()
        println("Result is: $result")
    }
    println("run main")
}

